<?php
// 兑换码功能迁移文件
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('redemption_codes', function (Blueprint $table) {
            $table->id();
            $table->string('code', 32)->unique()->comment('兑换码，全局唯一，随机生成');

            // 兑换类型枚举
            $table->enum('type', ['time_access', 'discount', 'product_exchange'])->comment('兑换类型：时长权限、抵扣金额、兑换商品');

            // 状态枚举
            $table->enum('status', ['unused', 'used', 'expired', 'disabled'])->default('unused')->comment('状态');

            // 时间字段

            $table->timestamp('expired_at')->nullable()->comment('过期时间');
            $table->timestamp('used_at')->nullable()->comment('核销时间');

            // 使用关联
            $table->unsignedBigInteger('used_user_id')->nullable()->comment('使用该码的用户ID');
            $table->unsignedBigInteger('used_order_id')->nullable()->comment('关联的订单ID（如适用）');

            // 附加信息，根据type不同而不同
            $table->json('metadata')->nullable()->comment('附加信息，根据type不同而不同');

            $table->timestamps();
            
            // 索引
            $table->index('code', 'idx_code');
            $table->index('status', 'idx_status');
            $table->index('used_user_id', 'idx_used_user');
            $table->index('expired_at', 'idx_expired');
            $table->index('type', 'idx_type');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('redemption_codes');
    }
};